
# include "SocketUnix.h"

SocketImpl::SocketImpl()
{
}

SocketImpl::~SocketImpl()
{
}

SocketImpl::SocketImpl(SocketImpl const & impl)
  : _fd(impl._fd),
    _domain(impl._domain),
    _type(impl._type),
    sin(impl.sin),
    len(impl.len)
{
  
}

SocketImpl& SocketImpl::operator=(SocketImpl const & impl)
{
  if (this != &impl)
    {
      _fd = impl._fd;
      _domain = impl._domain;
      _type = impl._type;
      sin = impl.sin;
      len = impl.len;
    }
  return *this;
}

void SocketImpl::open(int domain, int type)
{
  _fd = socket(domain, type, 0);
  _domain = domain;
  _type = type;
}

void SocketImpl::bind(int port, char *addr)
{
  if (addr == NULL)
    sin.sin_addr.s_addr = INADDR_ANY;
  else
    sin.sin_addr.s_addr = inet_addr(addr);
  sin.sin_family = _domain;
  sin.sin_port = port;

  ::bind(_fd, (sockaddr *)&sin, sizeof(sin));
}

void SocketImpl::listen(int backlog)
{
  ::listen(_fd, backlog);
}

void SocketImpl::accept(ISocket *sock)
{
  SocketImpl *csock;

  csock = dynamic_cast<SocketImpl *>(sock);
  csock->len = sizeof(csock->sin);
  csock->_fd = ::accept(_fd, (sockaddr *)&csock->sin, &csock->len);
}

void SocketImpl::connect(int port, char *addr)
{
  sin.sin_addr.s_addr = inet_addr(addr);
  sin.sin_family = _domain;
  sin.sin_port = port;

  ::connect(_fd, (sockaddr *)&sin, sizeof(sin));
}

int SocketImpl::send(const void *msg, size_t len)
{
  return ::send(_fd, msg, len, 0);
}

int SocketImpl::recv(void *buf, size_t len)
{
  return ::recv(_fd, buf, len, 0);
}

void SocketImpl::close()
{
  ::close(_fd);
}
